package com.hotel.servlet;

import com.alibaba.fastjson.JSON;
import com.hotel.bean.Room;
import com.hotel.service.RoomService;
import com.hotel.utils.ResultVo;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.print.Book;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/room")
public class RoomServlet extends BaseServlet{
    private RoomService rs = new RoomService();
    private ResultVo vo = null;
    //查询所有客房
    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //调用dao层的查询所有方法
        List<Room> list = rs.selectAll();
        vo= new ResultVo(200,"查询成功",list);
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    //添加客房
    public void addRoom(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        //获取数据
        Map<String, String[]> map = req.getParameterMap();
        //创建room对象
        Room room = new Room();
        //将数据放到room对象中
        BeanUtils.populate(room,map);
        //调用service层方法
        int add = rs.add(room);
        if (add>0){
            vo = new ResultVo(200,"添加成功",add);
        }else{
            vo = new ResultVo(500,"添加失败",add);

        }
        //将数据转换成json字符串
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    //数据回显
    public void findById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取rid
        String rid = req.getParameter("rid");
        //根据id查询客房的所有信息
        Room room = rs.selectById(Integer.parseInt(rid));
        vo= new ResultVo(200,"查询成功",room);
        //转换
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    //修改客房信息
    public void updateRoom(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        //获取数据
        Map<String, String[]> map = req.getParameterMap();
        Room room = new Room();
        BeanUtils.populate(room,map);
        //调用service层方法
        int i = rs.updateRoom(room);
        if (i>0){
            vo=new ResultVo(200,"修改成功",i);
        }else{
            vo=new ResultVo(500,"修改失败",i);
        }
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    //删除客房信息
    public void deleteRoom(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String rid = req.getParameter("rid");
        int i = rs.deleteById(Integer.parseInt(rid));
        if (i>0){
            vo=new ResultVo(200,"删除成功",i);
        }else{
            vo = new ResultVo(500,"删除失败",i);
        }
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
}
